package cn.quevo.ucenter.core.entity;

import java.util.LinkedHashMap;
import java.util.Map;

import cn.quevo.core.entity.ResultEntity;
import cn.quevo.core.enums.EnumsInterface;
import cn.quevo.core.exception.CustomException;
import cn.quevo.core.lang.JSONUtils;
import cn.quevo.core.lang.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class OauthResponse extends ResultEntity {

    /**
     * 
     */
    private static final long serialVersionUID = 4455682008153145300L;

    private Map<String, String> params = new LinkedHashMap<>();
    private String redirectUri; // 跳转URL

    public OauthResponse(CustomException exception) {
        super(exception);
    }

    public OauthResponse(EnumsInterface enums) {
        super(enums);
    }

    public OauthResponse(Integer status, String msg) {
        super(status, msg);
    }

    public OauthResponse set(String key, String value) {
        this.params.put(key, value);
        return this;
    }

    public Map<String,String> buildJsonBody() {
        return this.params;
    }

    public Map<String,String> buildJson() {
        this.set("status", String.valueOf(super.getStatus())).set("msg", super.getMsg());
        return buildJsonBody();
    }

    @Override
    public String toString() {
        return JSONUtils.format(buildJson());
    }

    public String getLocationUri() {
        if (StringUtils.isBlank(redirectUri) || StringUtils.isEmpty(this.params)) {
            return this.redirectUri;
        }
        StringBuffer requestParams = new StringBuffer();
        for (Map.Entry<String, String> entry : this.params.entrySet()) {
            requestParams.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        if (this.redirectUri.indexOf("?") != -1) {
            return "?" + requestParams.delete(requestParams.length() - 1, requestParams.length()).toString();
        }
        return "&" + requestParams.delete(requestParams.length() - 1, requestParams.length()).toString();
    }

    public OauthResponse setAccessToken(String accessToken) {
        this.set("accessToken", accessToken);
        return this;
    }
    public OauthResponse setRefreshToken(String refreshToken) {
        this.set("refreshToken", refreshToken);
        return this;
    }
    public OauthResponse setExpiresIn(Long expiresIn) {
        this.set("expiresIn", String.valueOf(expiresIn));
        return this;
    }
    
    public OauthResponse setIssuedAt(Long issuedAt) {
        this.set("issuedAt", String.valueOf(issuedAt));
        return this;
    }

    public OauthResponse setSubjectId(Long subjectId) {
        this.set("subjectId", String.valueOf(subjectId));
        return this;
    }
}
